<template>
    <view class="page-container">
        <!-- 顶部导航栏 -->
        <view class="nav-bar bg-primary text-white shadow-md">
            <uni-icons type="arrowleft" size="24" color="#fff" @click="handleBack"></uni-icons>
            <text class="nav-title font-medium">发布失物信息</text>
            <text class="nav-publish" @click="handlePublish">发布</text>
        </view>

        <!-- 类型切换标签 -->
        <view class="tab-bar bg-white shadow-sm">
            <view 
                :class="['tab-item flex-1 justify-center items-center py-4 text-base', activeTab === 'found' ? 'text-primary border-b-2 border-primary font-medium' : 'text-gray-500']" 
                @click="switchTab('found')">
                失物招领
            </view>
            <view 
                :class="['tab-item flex-1 justify-center items-center py-4 text-base', activeTab === 'lost' ? 'text-primary border-b-2 border-primary font-medium' : 'text-gray-500']" 
                @click="switchTab('lost')">
                寻物启事
            </view>
        </view>

        <!-- 内容区域 -->
        <scroll-view class="content flex-1 bg-gray-50 pb-32" scroll-y>
            <!-- 标题输入 -->
            <view class="form-section bg-white rounded-lg shadow-sm mx-4 mt-4 overflow-hidden">
                <view class="section-title px-6 py-4 text-gray-700 font-medium">标题</view>
                <view class="form-card px-6 py-2">
                    <view class="form-item">
                        <input 
                            v-model="currentForm.title" 
                            placeholder="请输入简洁明了的标题" 
                            placeholder-class="text-gray-400"
                            class="w-full text-gray-800 py-3" 
                            @input="validateField('title')" 
                        />
                        <text v-if="formErrors.title" class="error-text text-red-500 text-xs mt-1 block">{{ formErrors.title }}</text>
                    </view>
                </view>
            </view>

            <!-- 物品类别选择（带图标） -->
            <view class="form-section bg-white rounded-lg shadow-sm mx-4 mt-4 overflow-hidden">
                <view class="section-title px-6 py-4 text-gray-700 font-medium">物品类别</view>
                <view class="form-card px-6 py-2">
                    <view class="form-item category-picker">
                        <picker 
                            mode="selector" 
                            :range="categoryOptions" 
                            :range-key="'categoryName'"
                            :value="currentForm.categoryId" 
                            @change="handleCategoryChange"
                        >
                            <view class="picker-text category-picker-text flex justify-between items-center py-3">
                                <view class="flex items-center">
                                    <uni-icons 
                                        :type="categoryOptions[currentForm.categoryId]?.icon || 'questioncircle'"
                                        size="16" 
                                        color="#87CEEB" 
                                    />
                                    <text class="ml-2 text-gray-800">
                                        {{ categoryOptions[currentForm.categoryId]?.categoryName || '请选择物品类别' }}
                                    </text>
                                </view>
                                <uni-icons type="arrowdown" size="14" color="#999" />
                            </view>
                        </picker>
                    </view>
                </view>
            </view>

            <!-- 地图定位区域 -->
            <view class="location-section bg-white rounded-lg shadow-sm mx-4 mt-4 overflow-hidden">
                <view class="section-title px-6 py-4 text-gray-700 font-medium">位置信息</view>
                <view class="form-card px-6 py-4">
                    <view class="location-content flex items-center mb-4">
                        <view class="flex-1">
                            <text v-if="isAutoLocated" class="location-text text-gray-800 py-2 block">{{autoLocationName}}</text>
                            <input 
                                v-else-if="!isAutoLocated && !isManuallyLocated" 
                                placeholder="请输入位置信息"
                                placeholder-class="text-gray-400" 
                                class="w-full bg-gray-100 rounded-lg py-2 px-3"
                                @blur="handleLocationBlur" 
                                v-model="inputLocation" 
                                @input="handleLocationInput" 
                            />
                            <text v-else class="location-placeholder text-gray-500 py-2 block">{{manualLocationName}}</text>
                        </view>
                    </view>
                    <view class="location-buttons flex justify-between gap-3">
                        <button 
                            class="location-btn auto-btn flex-1 bg-primary/10 text-primary rounded-lg py-2 flex items-center justify-center" 
                            @click="getCurrentLocation"
                            :loading="isLoadingLocation"
                        >
                            <uni-icons type="location" size="16" color="#87CEEB"></uni-icons>
                            <text class="ml-2">自动定位</text>
                        </button>
                        <button 
                            class="location-btn manual-btn flex-1 bg-white border border-primary text-primary rounded-lg py-2 flex items-center justify-center" 
                            @click="chooseLocation"
                        >
                            <uni-icons type="map" size="16" color="#87CEEB"></uni-icons>
                            <text class="ml-2">手动选择</text>
                        </button>
                    </view>
                    <view class="form-item mt-4" v-if="currentLocation">
                        <text class="item-label block text-gray-600 mb-2">详细地址</text>
                        <input 
                            v-model="currentForm.detailAddress" 
                            placeholder="请输入详细地址（选填）"
                            placeholder-class="text-gray-400" 
                            class="w-full bg-gray-100 rounded-lg py-2 px-3"
                        />
                    </view>
                </view>
            </view>

            <!-- 图片上传区域 -->
            <view class="upload-section bg-white rounded-lg shadow-sm mx-4 mt-4 overflow-hidden">
                <view class="section-title px-6 py-4 text-gray-700 font-medium">上传物品图片</view>
                <view class="upload-area px-6 py-4">
                    <view class="grid grid-cols-4 gap-3">
                        <view 
                            v-for="(item, index) in images" 
                            :key="index" 
                            class="image-preview relative rounded-lg overflow-hidden"
                        >
                            <image :src="item" mode="aspectFill" class="w-full h-full"></image>
                            <view 
                                class="absolute top-2 right-2 bg-black/50 rounded-full w-6 h-6 flex items-center justify-center cursor-pointer"
                                @click.stop="handleDeleteImage(index)"
                            >
                                <uni-icons type="close" size="12" color="#fff"></uni-icons>
                            </view>
                        </view>
                        <view 
                            v-if="images.length < 9" 
                            class="upload-btn rounded-lg border-2 border-dashed border-gray-300 flex flex-col items-center justify-center h-28 cursor-pointer"
                            @click="handleChooseImage"
                        >
                            <uni-icons type="camera" size="28" color="#87CEEB"></uni-icons>
                            <text class="upload-text text-gray-500 text-xs mt-1">选择{{9 - images.length}}张图片</text>
                        </view>
                    </view>
                    <view v-if="images.length >= 9" class="upload-limit-tip text-center mt-3">
                        <text class="limit-text text-gray-500 text-xs">最多上传9张图片</text>
                    </view>
                </view>
            </view>

            <!-- 上传进度显示 -->
            <view v-if="uploadingImage" class="upload-progress-container bg-white rounded-lg shadow-sm mx-4 mt-4 p-6">
                <view class="progress-title text-gray-700 font-medium mb-4">图片上传中 {{uploadProgressIndex + 1}}/{{images.length}}</view>
                <view class="progress-item">
                    <text class="progress-filename text-gray-600 block mb-2">{{getFileName(uploadingImage)}}</text>
                    <view class="progress-bar h-2 bg-gray-200 rounded-full overflow-hidden">
                        <view class="progress-inner h-full bg-primary" :style="{width: uploadProgress + '%'}"></view>
                    </view>
                    <text class="progress-percent text-gray-500 text-xs mt-2 block">{{uploadProgress}}%</text>
                </view>
                <view v-if="uploadErrors.length > 0" class="upload-error mt-4">
                    <text class="error-text text-red-500 text-sm">{{uploadErrors[0]}}</text>
                </view>
            </view>
            
            <!-- 失物招领表单 -->
            <view v-if="activeTab === 'found'">
                <view class="form-section bg-white rounded-lg shadow-sm mx-4 mt-4 overflow-hidden">
                    <view class="section-title px-6 py-4 text-gray-700 font-medium">拾获信息</view>
                    <view class="form-card px-6 py-2">
                        <view class="form-item flex flex-col items-start py-3 border-b border-gray-100">
                            <text class="item-label text-gray-600 mb-2">拾获日期</text>
                            <picker 
                                mode="date" 
                                :value="formData.found.foundDate" 
                                @change="handleFoundDateChange"
                                class="w-full"
                            >
                                <view class="picker-text flex justify-between items-center py-2 bg-gray-100 rounded-lg px-3 w-full">
                                    <text class="text-gray-800">
                                        {{ formData.found.foundDate || '请选择拾获日期' }}
                                    </text>
                                    <uni-icons type="arrowdown" size="14" color="#999" />
                                </view>
                            </picker>
                        </view>
                        <view class="form-item flex flex-col items-start py-3 border-b border-gray-100">
                            <text class="item-label text-gray-600 mb-2">拾获时间</text>
                            <picker 
                                mode="time" 
                                :value="formData.found.foundTime" 
                                @change="handleFoundTimeChange"
                                class="w-full"
                            >
                                <view class="picker-text flex justify-between items-center py-2 bg-gray-100 rounded-lg px-3 w-full">
                                    <text class="text-gray-800">
                                        {{ formData.found.foundTime || '请选择拾获时间' }}
                                    </text>
                                    <uni-icons type="arrowdown" size="14" color="#999" />
                                </view>
                            </picker>
                        </view>
                        <view class="form-item flex flex-col items-start py-3">
                            <text class="item-label text-gray-600 mb-2">物品描述</text>
                            <textarea 
                                v-model="formData.found.description" 
                                placeholder="请详细描述物品特征"
                                placeholder-class="text-gray-400" 
                                class="w-full bg-gray-100 rounded-lg py-2 px-3 min-h-[100rpx]"
                                @input="validateField('description')" 
                            />
                            <text v-if="formErrors.description" class="error-text text-red-500 text-xs mt-1 block">{{ formErrors.description }}</text>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 寻物启事表单 -->
            <view v-if="activeTab === 'lost'">
                <view class="form-section bg-white rounded-lg shadow-sm mx-4 mt-4 overflow-hidden">
                    <view class="section-title px-6 py-4 text-gray-700 font-medium">丢失信息</view>
                    <view class="form-card px-6 py-2">
                        <view class="form-item flex flex-col items-start py-3 border-b border-gray-100">
                            <text class="item-label text-gray-600 mb-2">丢失日期</text>
                            <picker 
                                mode="date" 
                                :value="formData.lost.lostDate" 
                                @change="handleLostDateChange"
                                class="w-full"
                            >
                                <view class="picker-text flex justify-between items-center py-2 bg-gray-100 rounded-lg px-3 w-full">
                                    <text class="text-gray-800">
                                        {{ formData.lost.lostDate || '请选择丢失日期' }}
                                    </text>
                                    <uni-icons type="arrowdown" size="14" color="#999" />
                                </view>
                            </picker>
                        </view>
                        <view class="form-item flex flex-col items-start py-3 border-b border-gray-100">
                            <text class="item-label text-gray-600 mb-2">丢失时间</text>
                            <picker 
                                mode="time" 
                                :value="formData.lost.lostTime" 
                                @change="handleLostTimeChange"
                                class="w-full"
                            >
                                <view class="picker-text flex justify-between items-center py-2 bg-gray-100 rounded-lg px-3 w-full">
                                    <text class="text-gray-800">
                                        {{ formData.lost.lostTime || '请选择丢失时间' }}
                                    </text>
                                    <uni-icons type="arrowdown" size="14" color="#999" />
                                </view>
                            </picker>
                        </view>
                        <view class="form-item flex flex-col items-start py-3">
                            <text class="item-label text-gray-600 mb-2">物品描述</text>
                            <textarea 
                                v-model="formData.lost.description" 
                                placeholder="请详细描述物品特征"
                                placeholder-class="text-gray-400" 
                                class="w-full bg-gray-100 rounded-lg py-2 px-3 min-h-[100rpx]"
                                @input="validateField('description')" 
                            />
                            <text v-if="formErrors.description" class="error-text text-red-500 text-xs mt-1 block">{{ formErrors.description }}</text>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 联系方式区域 -->
            <view class="contact-section bg-white rounded-lg shadow-sm mx-4 mt-4 overflow-hidden mb-4">
                <view class="section-title px-6 py-4 text-gray-700 font-medium">联系方式</view>
                <view class="form-card px-6 py-2">
                    <view class="form-item flex flex-col items-start py-3">
                        <text class="item-label text-gray-600 mb-2">联系方式</text>
                        <input 
                            v-model="contactData.contactWay" 
                            placeholder="请输入手机号码或其他联系方式"
                            placeholder-class="text-gray-400" 
                            class="w-full bg-gray-100 rounded-lg py-2 px-3"
                            @input="validateField('contactWay')" 
                        />
                        <text v-if="formErrors.contactWay" class="error-text text-red-500 text-xs mt-1 block">{{ formErrors.contactWay }}</text>
                    </view>
                    <view class="privacy-item py-4 flex items-center">
                        <radio-group @change="handlePrivacyChange" class="flex items-center">
                            <label class="radio-label flex items-center mr-8">
                                <radio :checked="contactData.isPublic" color="#87CEEB" value="true" />
                                <text class="ml-2 text-gray-600">公开联系方式</text>
                            </label>
                            <label class="radio-label flex items-center">
                                <radio :checked="!contactData.isPublic" color="#87CEEB" value="false" />
                                <text class="ml-2 text-gray-600">仅平台可见</text>
                            </label>
                        </radio-group>
                    </view>
                </view>
            </view>
        </scroll-view>

        <!-- 底部提交按钮 -->
        <view class="fixed bottom-0 left-0 right-0 bg-white p-4 shadow-lg">
            <button 
                :disabled="!canSubmit || isUploading" 
                :class="['submit-btn w-full py-4 rounded-full text-white font-medium', canSubmit ? 'bg-primary' : 'bg-gray-300']" 
                @click="handleSubmit"
            >
                发布{{ activeTab === 'found' ? '失物招领' : '寻物启事' }}
            </button>
        </view>
    </view>
</template>

<script lang="ts" setup>
    import { ref, computed, onMounted, watch } from 'vue';

    // 物品类别选项
    const categoryOptions = ref([]);
    const isLoadingCategories = ref(false);
    const categoryError = ref('');

    // 表单类型定义 - 调整字段名与后端一致
    interface FoundForm {
        title: string;
        categoryId: number;
        description: string;
        foundDate: string;
        foundTime: string;
        foundLocation: string;
        foundLocationName: string;
        detailAddress: string;
        images: string[];
    }

    interface LostForm {
        title: string;
        categoryId: number;
        description: string;
        lostDate: string;
        lostTime: string;
        lostLocation: string;
        lostLocationName: string;
        detailAddress: string;
        images: string[];
    }

    // 表单数据
    const images = ref<string[]>([]);
    const activeTab = ref<'found' | 'lost'>('found');
    const currentLocation = ref('');
    const isLoadingLocation = ref(false);
    const isResolvingAddress = ref(false);

    // 定位状态
    const isAutoLocated = ref(false);
    const isManuallyLocated = ref(false);
    const autoLocationName = ref('');
    const manualLocationName = ref('');
    const inputLocation = ref('');

    // 表单验证错误
    const formErrors = ref({
        title: '',
        description: '',
        contactWay: '',
        location: ''
    });

    // 表单数据初始化 - 字段名与后端匹配
    const formData = ref<{
        found: FoundForm;
        lost: LostForm;
    }>({
        found: {
            title: '',
            categoryId: 0,
            description: '',
            foundDate: '',
            foundTime: '',
            foundLocation: '',
            foundLocationName: '',
            detailAddress: '',
            images: []
        },
        lost: {
            title: '',
            categoryId: 0,
            description: '',
            lostDate: '',
            lostTime: '',
            lostLocation: '',
            lostLocationName: '',
            detailAddress: '',
            images: []
        }
    });

    // 联系方式数据
    const contactData = ref({
        contactWay: '',
        isPublic: true,
    });

    // 当前表单计算属性
    const currentForm = computed(() => {
        return activeTab.value === 'found' ? formData.value.found : formData.value.lost;
    });

    // 提交验证
    const canSubmit = computed(() => {
        return (
            currentForm.value.title.trim() !== '' &&
            currentForm.value.categoryId !== undefined &&
            currentForm.value.description.trim() !== '' &&
            (activeTab.value === 'found' 
                ? (currentForm.value.foundDate && currentForm.value.foundTime) 
                : (currentForm.value.lostDate && currentForm.value.lostTime)) &&
            (isAutoLocated.value || isManuallyLocated.value || inputLocation.value.trim() !== '') &&
            contactData.value.contactWay.trim() !== '' &&
            Object.values(formErrors.value).every(msg => !msg)
        );
    });

    // 全局错误处理函数
    const handleApiError = (error: any, defaultMsg: string) => {
        console.error('API请求失败:', error);
        const message = error.message || defaultMsg;
        uni.showToast({
            title: message,
            icon: 'none',
        });
    };

    // 从本地存储获取用户ID
    const getUserId = () => {
        try {
            const userId = uni.getStorageSync('userId');
            if (!userId) {
                throw new Error('未找到用户ID，请先登录');
            }
            return userId;
        } catch (error) {
            console.error('获取用户ID失败:', error);
            uni.showToast({
                title: '请先登录',
                icon: 'none',
                duration: 2000
            });
            setTimeout(() => {
                uni.navigateTo({
                    url: '/pages/login/login'
                });
            }, 1500);
            return null;
        }
    };

    // 获取物品种类数据
    const fetchCategories = async () => {
        isLoadingCategories.value = true;
        try {
            const res = await uni.request({
                url: 'http://172.20.10.2:8080/api/Category/getAll',
                method: 'GET',
                header: {
                    'content-type': 'application/json',
                }
            });

            if (res.statusCode === 200) {
                const data = res.data;
                if (data.code === 200) {
                    categoryOptions.value = data.data;

                    if (categoryOptions.value.length > 0) {
                        currentForm.value.categoryId = 0;
                    }
                } else {
                    throw new Error(data.message || '获取物品种类失败');
                }
            } else {
                throw new Error('API请求失败');
            }
        } catch (error) {
            handleApiError(error, '获取物品种类失败，请稍后重试');
            categoryError.value = '获取物品种类失败，请稍后重试';
        } finally {
            isLoadingCategories.value = false;
        }
    };

    // 切换标签页
    const switchTab = (tab: 'found' | 'lost') => {
        activeTab.value = tab;
        // 重置位置信息
        currentLocation.value = '';
        currentForm.value.detailAddress = '';
        if (tab === 'found') {
            currentForm.value.foundLocation = '';
            currentForm.value.foundLocationName = '';
        } else {
            currentForm.value.lostLocation = '';
            currentForm.value.lostLocationName = '';
        }

        // 重置定位状态
        isAutoLocated.value = false;
        isManuallyLocated.value = false;
        autoLocationName.value = '';
        manualLocationName.value = '';
        inputLocation.value = '';
    };

    // 物品类别选择
    const handleCategoryChange = (e: any) => {
        currentForm.value.categoryId = parseInt(e.detail.value);
    };

    // 失物招领日期选择
    const handleFoundDateChange = (e: any) => {
        formData.value.found.foundDate = e.detail.value;
    };

    // 失物招领时间选择
    const handleFoundTimeChange = (e: any) => {
        formData.value.found.foundTime = e.detail.value;
    };

    // 寻物启事日期选择
    const handleLostDateChange = (e: any) => {
        formData.value.lost.lostDate = e.detail.value;
    };

    // 寻物启事时间选择
    const handleLostTimeChange = (e: any) => {
        formData.value.lost.lostTime = e.detail.value;
    };

    // 隐私设置变更
    const handlePrivacyChange = (e: any) => {
        contactData.value.isPublic = e.detail.value === 'true';
    };

    // 位置输入处理
    const handleLocationBlur = (e: any) => {
        if (inputLocation.value.trim()) {
            resolveAddressByInput();
        }
    };

    const handleLocationInput = (e: any) => {
        inputLocation.value = e.detail.value;
    };

    // 表单字段验证
    const validateField = (field: keyof typeof formErrors.value) => {
        const value = (field === 'contactWay' ? contactData.value.contactWay : currentForm.value[field as keyof FoundForm])?.trim() || '';

        switch (field) {
            case 'title':
                formErrors.value.title = value.length < 2 || value.length > 50
                    ? '请输入2-50个字符的标题'
                    : '';
                break;
            case 'description':
                formErrors.value.description = value.length < 10
                    ? '请详细描述物品特征，至少10个字符'
                    : '';
                break;
            case 'contactWay':
                formErrors.value.contactWay = !/^1[3-9]\d{9}$|^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value)
                    ? '请输入有效的手机号或邮箱'
                    : '';
                break;
            default:
                break;
        }
    };

    // 图片选择
    const handleChooseImage = async () => {
        try {
            const remaining = 9 - images.value.length;
            const res = await uni.chooseImage({
                count: remaining,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
            });
            images.value = [...images.value, ...res.tempFilePaths];
        } catch (error) {
            console.error('选择图片失败:', error);
            uni.showToast({
                title: '图片选择失败',
                icon: 'none',
            });
        }
    };

    // 删除图片
    const handleDeleteImage = (index: number) => {
        images.value.splice(index, 1);
    };

    // 预览图片
    const handlePreviewImage = (index: number) => {
        uni.previewImage({
            current: index,
            urls: images.value,
        });
    };

    // 自动获取当前位置
    const getCurrentLocation = async () => {
        if (isLoadingLocation.value) return;

        isLoadingLocation.value = true;
        try {
            // 检查权限
            const authRes = await uni.getSetting({
                success: (res) => res.authSetting['scope.userLocation']
            });
            
            if (!authRes) {
                await uni.authorize({
                    scope: 'scope.userLocation',
                    fail: () => {
                        throw new Error('用户拒绝了定位权限');
                    }
                });
            }
            
            const locationRes = await uni.getLocation({
                type: 'gcj02',
            });

            const geocodeRes = await resolveLocationToAddress(
                locationRes.latitude,
                locationRes.longitude
            );

            if (geocodeRes && geocodeRes.address) {
                autoLocationName.value = geocodeRes.address;
                currentLocation.value = geocodeRes.address;
                
                // 根据当前标签页绑定到对应表单字段
                if (activeTab.value === 'found') {
                    currentForm.value.foundLocation = `${locationRes.latitude},${locationRes.longitude}`;
                    currentForm.value.foundLocationName = geocodeRes.address;
                } else {
                    currentForm.value.lostLocation = `${locationRes.latitude},${locationRes.longitude}`;
                    currentForm.value.lostLocationName = geocodeRes.address;
                }

                isAutoLocated.value = true;
                isManuallyLocated.value = false;
                formErrors.value.location = '';

                uni.showToast({
                    title: '定位成功',
                    icon: 'success',
                    duration: 1500
                });
            } else {
                throw new Error('获取地址失败');
            }
        } catch (error) {
            console.error('定位失败:', error);
            formErrors.value.location = '定位失败，请手动选择位置或直接输入';
            uni.showToast({
                title: '定位失败，请手动选择位置或直接输入',
                icon: 'none',
                duration: 1500
            });
        } finally {
            isLoadingLocation.value = false;
        }
    };

    // 手动选择位置
    const chooseLocation = async () => {
        if (isLoadingLocation.value) return;
        
        isLoadingLocation.value = true;
        try {
            // 检查权限
            const authRes = await uni.getSetting({
                success: (res) => res.authSetting['scope.userLocation']
            });
            
            if (!authRes) {
                await uni.authorize({
                    scope: 'scope.userLocation',
                    fail: () => {
                        throw new Error('用户拒绝了定位权限');
                    }
                });
            }
            
            const res = await uni.chooseLocation();
            
            manualLocationName.value = res.name;
            currentLocation.value = res.name;
            
            // 根据当前标签页绑定到对应表单字段
            if (activeTab.value === 'found') {
                currentForm.value.foundLocation = `${res.latitude},${res.longitude}`;
                currentForm.value.foundLocationName = res.name;
            } else {
                currentForm.value.lostLocation = `${res.latitude},${res.longitude}`;
                currentForm.value.lostLocationName = res.name;
            }
            
            currentForm.value.detailAddress = res.address;

            isAutoLocated.value = false;
            isManuallyLocated.value = true;
            formErrors.value.location = '';
            
            uni.showToast({
                title: '位置选择成功',
                icon: 'success',
                duration: 1500
            });
        } catch (error) {
            console.error('选择位置失败:', error);
            formErrors.value.location = '位置选择失败，请重试';
            uni.showToast({
                title: '位置选择失败，请重试',
                icon: 'none',
                duration: 1500
            });
        } finally {
            isLoadingLocation.value = false;
        }
    };

    // 地址解析
    const resolveAddressByInput = async () => {
        if (!inputLocation.value.trim() || isResolvingAddress.value) return;

        isResolvingAddress.value = true;
        try {
            const res = await uni.request({
                url: 'http://172.20.10.2:8080/api/map/geocode',
                method: 'GET',
                data: {
                    address: inputLocation.value.trim()
                },
                header: {
                    'content-type': 'application/json'
                }
            });

            if (res.statusCode === 200) {
                const data = res.data;
                if (data.code === 200 && data.result && data.result.location) {
                    const location = data.result.location;
                    
                    // 根据当前标签页绑定到对应表单字段
                    if (activeTab.value === 'found') {
                        currentForm.value.foundLocation = `${location.lat},${location.lng}`;
                        currentForm.value.foundLocationName = inputLocation.value;
                    } else {
                        currentForm.value.lostLocation = `${location.lat},${location.lng}`;
                        currentForm.value.lostLocationName = inputLocation.value;
                    }

                    isAutoLocated.value = false;
                    isManuallyLocated.value = false;
                    currentLocation.value = inputLocation.value;
                    formErrors.value.location = '';

                    uni.showToast({
                        title: '地址解析成功',
                        icon: 'success',
                        duration: 1500
                    });
                } else {
                    throw new Error('地址解析失败');
                }
            } else {
                throw new Error('API请求失败');
            }
        } catch (error) {
            handleApiError(error, '无法解析该地址，请检查输入');
            formErrors.value.location = '无法解析该地址，请检查输入';
        } finally {
            isResolvingAddress.value = false;
        }
    };

    // 逆地址解析
    const resolveLocationToAddress = async (latitude: number, longitude: number) => {
        try {
            const res = await uni.request({
                url: 'http://172.20.10.2:8080/api/map/reverseGeocode',
                method: 'GET',
                data: {
                    latitude,
                    longitude
                },
                header: {
                    'content-type': 'application/json'
                }
            });

            if (res.statusCode === 200) {
                const data = res.data;
                if (data.code === 200 && data.result && data.result.address) {
                    return data.result;
                }
            }
            return null;
        } catch (error) {
            handleApiError(error, '地址解析失败');
            return null;
        }
    };

    // 串行上传图片到后端
    const isUploading = ref(false);
    const uploadingImage = ref('');
    const uploadProgress = ref(0);
    const uploadProgressIndex = ref(0);
    const uploadErrors = ref<string[]>([]);
    
    const uploadImagesToServer = async () => {
        if (images.value.length === 0) return [];
        
        isUploading.value = true;
        uploadErrors.value = [];
        const serverUrls = [];
        
        try {
            for (let i = 0; i < images.value.length; i++) {
                uploadProgressIndex.value = i;
                uploadingImage.value = images.value[i];
                uploadProgress.value = 0;
                
                const serverUrl = await new Promise<string>((resolve, reject) => {
                    const uploadTask = uni.uploadFile({
                        url: 'http://172.20.10.2:8080/api/upload/image',
                        filePath: images.value[i],
                        name: 'image',
                        formData: {
                            userId: getUserId()
                        },
                        success: (res) => {
                            if (res.statusCode === 200) {
                                const data = JSON.parse(res.data);
                                if (data.code === 200 && data.data && data.data.url) {
                                    resolve(data.data.url);
                                } else {
                                    reject(new Error(data.message || '图片上传失败'));
                                }
                            } else {
                                reject(new Error(`服务器返回错误: ${res.statusCode}`));
                            }
                        },
                        fail: (err) => {
                            reject(new Error(`上传失败: ${err.errMsg}`));
                        }
                    });
                    
                    uploadTask.onProgressUpdate((res) => {
                        uploadProgress.value = res.progress;
                    });
                });
                
                serverUrls.push(serverUrl);
            }
            
            return serverUrls;
        } catch (error) {
            console.error('上传图片失败:', error);
            uploadErrors.value.push(error.message);
            throw error;
        } finally {
            isUploading.value = false;
            uploadingImage.value = '';
            uploadProgress.value = 0;
            uploadProgressIndex.value = 0;
        }
    };

    // 处理表单提交 - 关键修改点：数据结构与后端实体类匹配
    const handleSubmit = async () => {
        // 表单验证
        if (!canSubmit.value) {
            const firstError = Object.values(formErrors.value).find(msg => msg);
            uni.showToast({
                title: firstError || '请完成必填信息',
                icon: 'none',
                duration: 1500
            });
            return;
        }
        
        const userId = getUserId();
        if (!userId) return;
        
        uni.showLoading({
            title: '发布中...',
            mask: true
        });
        
        try {
            // 第一步：串行上传所有图片到服务器
            const imageUrls = await uploadImagesToServer();
            
            if (uploadErrors.value.length > 0) {
                throw new Error(`图片上传失败: ${uploadErrors.value[0]}`);
            }
				
            // 第二步：准备符合后端实体类的JSON数据（字段名与后端完全一致）
            let publishData = null;
            if (activeTab.value === 'found') {
                publishData = {
                    userId: userId,
                    categoryId: categoryOptions.value[currentForm.value.categoryId]?.categoryId || 0,
                    title: currentForm.value.title,
                    description: currentForm.value.description,
                    foundTime: `${currentForm.value.foundDate} ${currentForm.value.foundTime}:00`,
                    foundLocation: currentForm.value.foundLocationName + currentForm.value.detailAddress,
                    contactWay: contactData.value.contactWay,
                    status: 1, // 1=待领取状态
                    images: imageUrls.map(url => ({ url })), // 转换为后端需要的Map列表
                    // CreateTime和UpdateTime由后端自动生成，前端不传递
                };
            } else {
                publishData = {
                    userId: userId,
                    categoryId: categoryOptions.value[currentForm.value.categoryId]?.categoryId || 0,
                    title: currentForm.value.title,
                    description: currentForm.value.description,
                    lostTime: `${currentForm.value.lostDate} ${currentForm.value.lostTime}:00`,
                    lostLocation: currentForm.value.lostLocationName + currentForm.value.detailAddress,
                    contactWay: contactData.value.contactWay,
                    status: 1, // 1=待找回状态
                    images: imageUrls.map(url => ({ url })),
                };
            }
            console.log(publishData);
            
            // 第三步：发送POST请求到后端（使用application/json格式）
            const res = await uni.request({
                url: activeTab.value === 'found' 
                    ? 'http://172.20.10.2:8080/api/FoundItem/add' 
                    : 'http://172.20.10.2:8080/api/LostItem/add',
                method: 'POST',
                data: publishData,
                header: {
                    'Content-Type': 'application/json',
                }
            });
            
            if (res.statusCode === 200) {
                const data = res.data;
                if (data.code === 200) {
                    uni.showToast({
                        title: '发布成功',
                        icon: 'success',
                        duration: 2000
                    });
                    setTimeout(() => {
                        resetForm();
                        uni.switchTab({
                            url: "/pages/publish/publish"
                        });
                    }, 1500);
                } else {
                    throw new Error(data.message || '发布失败');
                }
            } else {
                throw new Error(`服务器返回错误状态码: ${res.statusCode}`);
            }
        } catch (error) {
            console.error('发布失败:', error);
            handleApiError(error, '发布失败，请稍后重试');
        } finally {
            uni.hideLoading();
        }
    };

    // 重置表单
    const resetForm = () => {
        formData.value = {
            found: {
                title: '',
                categoryId: 0,
                description: '',
                foundDate: '',
                foundTime: '',
                foundLocation: '',
                foundLocationName: '',
                detailAddress: '',
                images: []
            },
            lost: {
                title: '',
                categoryId: 0,
                description: '',
                lostDate: '',
                lostTime: '',
                lostLocation: '',
                lostLocationName: '',
                detailAddress: '',
                images: []
            }
        };

        contactData.value = {
            contactWay: '',
            isPublic: true,
        };

        images.value = [];
        currentLocation.value = '';
        isAutoLocated.value = false;
        isManuallyLocated.value = false;
        autoLocationName.value = '';
        manualLocationName.value = '';
        inputLocation.value = '';
        formErrors.value = {
            title: '',
            description: '',
            contactWay: '',
            location: ''
        };
    };

    // 返回处理
    const handleBack = () => {
        uni.navigateBack();
    };

    // 快捷发布处理
    const handlePublish = () => {
        if (canSubmit.value) {
            handleSubmit();
        }
    };

    // 辅助函数：从路径获取文件名
    const getFileName = (path: string) => {
        return path.substring(path.lastIndexOf('/') + 1);
    };

    // 页面加载时获取物品种类
    onMounted(() => {
        // 设置默认日期为今天
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        formData.value.found.foundDate = `${year}-${month}-${day}`;
        formData.value.lost.lostDate = `${year}-${month}-${day}`;

        // 设置默认时间为当前时间
        const hours = String(today.getHours()).padStart(2, '0');
        const minutes = String(today.getMinutes()).padStart(2, '0');
        formData.value.found.foundTime = `${hours}:${minutes}`;
        formData.value.lost.lostTime = `${hours}:${minutes}`;

        // 获取物品种类
        fetchCategories();
    });
</script>

<style>
    page {
        height: 100%;
    }

    .page-container {
        display: flex;
        flex-direction: column;
        height: 100%;
        background-color: #f5f5f5;
    }

    .nav-bar {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 88rpx;
        padding: 0 32rpx;
        background-color: #87CEEB;
        color: #fff;
        position: relative;
        z-index: 10;
    }

    .nav-title {
        font-size: 18px;
        font-weight: 500;
    }

    .nav-publish {
        font-size: 16px;
    }

    .tab-bar {
        display: flex;
        justify-content: center;
        height: 88rpx;
        background-color: #fff;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
        position: relative;
        z-index: 9;
    }

    .tab-item {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 50%;
        font-size: 16px;
        color: #666;
        position: relative;
    }

    .tab-item.active {
        color: #87CEEB;
        font-weight: 500;
    }

    .tab-item.active::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 60rpx;
        height: 6rpx;
        background-color: #87CEEB;
        border-radius: 3rpx;
    }

    .content {
        flex: 1;
        overflow-y: auto;
        padding-bottom: 120rpx;
    }

    .form-section {
        margin-top: 24rpx;
        background-color: #fff;
    }

    .section-title {
        padding: 24rpx 32rpx;
        font-size: 15px;
        color: #333;
        font-weight: 500;
    }

    .form-card {
        padding: 0 32rpx;
    }

    .form-item {
        display: flex;
        align-items: center;
        padding: 24rpx 0;
        border-bottom: 1rpx solid #eee;
    }

    .form-item:last-child {
        border-bottom: none;
    }

    .item-label {
        width: 180rpx;
        font-size: 15px;
        color: #666;
    }

    .item-input {
        flex: 1;
        font-size: 15px;
        color: #333;
        height: 48rpx;
        line-height: 48rpx;
    }

    .item-textarea {
        flex: 1;
        font-size: 15px;
        color: #333;
        min-height: 120rpx;
        padding-top: 8rpx;
    }

    .placeholder {
        color: #999;
    }

    .picker-text {
        flex: 1;
        font-size: 15px;
        color: #333;
        text-align: right;
    }

    .category-picker-text {
        display: flex;
        align-items: center;
        justify-content: flex-end;
    }

    .category-picker-text uni-icons {
        margin-right: 12rpx;
    }

    .location-section {
        margin-top: 24rpx;
        background-color: #fff;
    }

    .location-item {
        flex-direction: column;
        align-items: flex-start;
        padding-bottom: 16rpx;
    }

    .location-content {
        width: 100%;
        display: flex;
        align-items: center;
        margin-bottom: 16rpx;
    }

    .location-text {
        flex: 1;
        font-size: 15px;
        color: #333;
        padding-right: 16rpx;
    }

    .location-input {
        flex: 1;
        font-size: 15px;
        color: #333;
        height: 48rpx;
        line-height: 48rpx;
        padding: 0 16rpx;
        background-color: #f5f5f5;
        border-radius: 8rpx;
    }

    .location-placeholder {
        flex: 1;
        font-size: 15px;
        color: #999;
        padding-right: 16rpx;
    }

    .location-buttons {
        width: 100%;
        display: flex;
        justify-content: space-between;
    }

    .location-btn {
        width: 48%;
        height: 64rpx;
        line-height: 64rpx;
        text-align: center;
        font-size: 14px;
        color: #87CEEB;
        border: 1rpx solid #87CEEB;
        border-radius: 8rpx;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .location-btn uni-icons {
        margin-right: 8rpx;
    }

    .auto-btn {
        background-color: rgba(135, 206, 235, 0.1);
    }

    .manual-btn {
        background-color: #fff;
    }

    .upload-section {
        margin-top: 24rpx;
        background-color: #fff;
    }

    .upload-area {
        display: flex;
        flex-wrap: wrap;
        padding: 0 32rpx 32rpx;
    }

    .image-preview {
        width: 160rpx;
        height: 160rpx;
        margin-right: 24rpx;
        margin-bottom: 24rpx;
        border-radius: 8rpx;
        overflow: hidden;
        position: relative;
    }

    .image-preview:nth-child(4n) {
        margin-right: 0;
    }

    .preview-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .delete-icon {
        position: absolute;
        top: 8rpx;
        right: 8rpx;
        background-color: rgba(0, 0, 0, 0.5);
        border-radius: 50%;
        padding: 6rpx;
        color: #fff;
    }

    .upload-btn {
        width: 160rpx;
        height: 160rpx;
        border: 2rpx dashed #ddd;
        border-radius: 8rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #999;
    }

    .upload-text {
        margin-top: 12rpx;
        font-size: 13px;
    }

    .upload-limit-tip {
        width: 160rpx;
        height: 160rpx;
        border: 2rpx dashed #ddd;
        border-radius: 8rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #999;
    }
    
    .limit-text {
        margin-top: 12rpx;
        font-size: 13px;
    }

    .contact-section {
        margin-top: 24rpx;
        background-color: #fff;
    }

    .privacy-item {
        padding: 24rpx 0;
        display: flex;
        align-items: center;
    }

    .radio-label {
        display: flex;
        align-items: center;
        margin-right: 64rpx;
    }

    .radio-label text {
        margin-left: 12rpx;
        font-size: 15px;
        color: #666;
    }

    .error-text {
        color: #f56c6c;
        font-size: 12px;
        margin-top: 8rpx;
    }

    .upload-progress-container {
        padding: 20rpx 32rpx;
        background-color: #fff;
        margin-top: 24rpx;
    }
    
    .progress-title {
        font-size: 15px;
        color: #333;
        margin-bottom: 16rpx;
    }
    
    .progress-item {
        margin-bottom: 16rpx;
    }
    
    .progress-filename {
        font-size: 14px;
        color: #666;
        margin-bottom: 8rpx;
    }
    
    .progress-bar {
        height: 10rpx;
        background-color: #eee;
        border-radius: 5rpx;
        overflow: hidden;
    }
    
    .progress-inner {
        height: 100%;
        background-color: #87CEEB;
        transition: width 0.3s;
    }
    
    .progress-percent {
        font-size: 12px;
        color: #999;
        margin-top: 8rpx;
    }
    
    .upload-error {
        margin-top: 16rpx;
    }

    .submit-btn-container {
        padding: 32rpx;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #fff;
        box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
    }

    .submit-btn {
        width: 100%;
        height: 88rpx;
        line-height: 88rpx;
        text-align: center;
        background-color: #ddd;
        color: #fff;
        font-size: 18px;
        border-radius: 44rpx;
    }

    .submit-btn.active {
        background-color: #87CEEB;
    }
</style>